//
//  UIControl+Extend.swift
//  ADKit
//
//  Created by Adoma on 2022/4/19.
//

import UIKit

private var EdgeInsetTop: UInt8 = 0
private var EdgeInsetLeft: UInt8 = 0
private var EdgeInsetRight: UInt8 = 0
private var EdgeInsetBottom: UInt8 = 0

extension UIControl {

    /// by ADKit
    @objc public func extendRespondEdge(round: CGFloat) {
        extendRespondEdge(top: round, bottom: round, left: round, right: round)
    }
    
    /// by ADKit
    @objc public func extendRespondEdge(top: CGFloat, bottom: CGFloat, left: CGFloat, right: CGFloat) {
        objc_setAssociatedObject(self, &EdgeInsetTop, top, .OBJC_ASSOCIATION_ASSIGN)
        objc_setAssociatedObject(self, &EdgeInsetLeft, left, .OBJC_ASSOCIATION_ASSIGN)
        objc_setAssociatedObject(self, &EdgeInsetRight, right, .OBJC_ASSOCIATION_ASSIGN)
        objc_setAssociatedObject(self, &EdgeInsetBottom, bottom, .OBJC_ASSOCIATION_ASSIGN)
    }
    
    private var extendRect: CGRect {
        
        let top = objc_getAssociatedObject(self, &EdgeInsetTop) as? CGFloat ?? 0
        let left = objc_getAssociatedObject(self, &EdgeInsetLeft) as? CGFloat ?? 0
        let right = objc_getAssociatedObject(self, &EdgeInsetRight) as? CGFloat ?? 0
        let bottom = objc_getAssociatedObject(self, &EdgeInsetBottom) as? CGFloat ?? 0
        
        var rect = bounds
        rect.origin.x = rect.origin.x - left
        rect.origin.y = rect.origin.y - top
        rect.size.width = rect.size.width + left + right
        rect.size.height = rect.size.height + top + bottom
        
        return rect
    }
    
    override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return extendRect.contains(point)
    }
}
